#include "qhostfactory.h"

#include "../shared/xmlobject.h"
#include "qabstracthost.h"

bool hostLessThan(tagHostInfo* info1, tagHostInfo *info2)
{
    return info1->m_index <info2->m_index;
}

QMap<QString,tagHostInfo*>  *m_meta_map;
QList<tagHostInfo*>         *m_metas;

QHostFactory::QHostFactory(const QString name,
                           const QString &type,
                           const QString &show_icon,
                           const QString &show_name,
                           const QString &show_group,
                           const QMetaObject *host,
                           int index)
{
    qDebug(host->className());
    register_host(name,type,show_icon,show_name,show_group,host,index);
}

void QHostFactory::register_host(const QString name,
                                 const QString &type,
                                 const QString &show_icon,
                                 const QString &show_name,
                                 const QString &show_group,
                                 const QMetaObject *host,
                                 int index)
{
    static bool b=false;
    if(!b)
    {
        m_meta_map=new QMap<QString,tagHostInfo*>();
        m_metas=new QList<tagHostInfo*>();
        b=true;
    }
    tagHostInfo *info=m_meta_map->value(name);
    if(info==NULL)
    {
        info=new tagHostInfo;
    }
    else
    {
        m_metas->removeAll(info);
    }
    info->m_host_object=host;
    info->m_name=name;
    info->m_type=type;
    info->m_show_icon=show_icon;
    info->m_show_name=show_name;
    info->m_show_group=show_group;
    info->m_index=index;
    m_meta_map->insert(name,info);
    m_metas->append(info);
}

void QHostFactory::sort()
{
    qStableSort(m_metas->begin(), m_metas->end(),hostLessThan);
}

QAbstractHost* QHostFactory::create_host(const QString &name)
{
    QAbstractHost* host=NULL;
    tagHostInfo *info=m_meta_map->value(name);
    if(info==NULL)
    {
        return NULL;
    }
    const QMetaObject* obj=info->m_host_object;

    if(obj!=NULL)
    {
        host=(QAbstractHost*)obj->newInstance();
        host->init();
        host->set_attribute(HOST_TYPE,name);
    }
    return host;
}

QList<tagHostInfo*> QHostFactory::get_host_info()
{
    return *m_metas;
}

QAbstractHost* QHostFactory::create_host(XMLObject *xml)
{
    if(xml==NULL)
    {
        return NULL;
    }

    QAbstractHost* ret=NULL;

    ret=create_host(xml->get_property(HOST_TYPE));
    if(ret!=NULL)
    {
        ret->from_object(xml);
    }
    return ret;
}

tagHostInfo* QHostFactory::get_host_info(const QString &name)
{
    return m_meta_map->value(name);
}
